package member.manager.impl;

import member.manager.IMemberManager;
import entities.Member;
import utils.BaseManager;

import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.persistence.Query;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: NGUYEN VAN NHAN
 * Date: 9/17/14
 * Time: 2:30 PM
 * Long Van Soft Solution Sjc.
 * To change this template use File | Settings | File Templates.
 */
@Stateless(name = "MemberManager")
@Remote(IMemberManager.class)
public class MemberManager extends BaseManager implements IMemberManager {
    @Override
    public void createMember(Member member) {
        if (null != member)
            getEntityManager().merge(member);
    }
    @Override
    public Member getMemberByEmail(String email){
        Query query = getEntityManager().createQuery("select m from Member m where m.email =:email");
        query.setParameter("email", email);
        List<Member> membersList = query.getResultList();
        if (null != membersList && membersList.size() > 0)
            return membersList.get(0);
        return null;
    }

    @Override
    public int getMemberIdByUid(String uid, String opt) {
        if (null != uid && null != opt) {
            Query query = null;
            if (opt.equals("facebook")) {
                query = getEntityManager().createQuery("select m.memberId from Member m where m.fb_uid =:uid");
                query.setParameter("uid", uid);
            }
//            if (opt.equals("googleplus")) {
//                query = getEntityManager().createQuery("select m.memberId from Member m where m.googleUid =:uid");
//                query.setParameter("uid", uid);
//            }
//            if (opt.equals("twitter")) {
//                query = getEntityManager().createQuery("select m.memberId from Member m where m.twitterId =:uid");
//                query.setParameter("uid", uid);
//            }

            List results = query.getResultList();
            if (results.size() > 0) {
                Integer memberId = (Integer) results.get(0);
                return memberId;
            }
        }
        return 0;
    }

    @Override
    public Member getMemberById(int memberId) {
        try {
            Query query = getEntityManager().createQuery("select m from Member m where m.memberId = :memberId");
            query.setParameter("memberId", memberId);
            Member members = (Member) query.getSingleResult();
            return members;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    @Override
    public String getClassName() {
        return getClass().getName();
    }
}
